import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver import ActionChains

# 1.打开浏览器
driver = webdriver.Chrome()

# 2.输入访问地址（URL）
driver.get("https://hmshop-test.itheima.net/")

# 放大浏览器页面
driver.maximize_window()

# 获取首页句柄
current_handle = driver.current_window_handle

# 点击登录连接
driver.find_element(By.CSS_SELECTOR, ".red").click()

# 获取登录页句柄
handles = driver.current_window_handle
# 切换
driver.switch_to.window(handles)

# 定位并输入手机号、密码、验证码
driver.find_element(By.CSS_SELECTOR, "#username").send_keys("18172128129")
driver.find_element(By.CSS_SELECTOR, "#password").send_keys("123456")
driver.find_element(By.CSS_SELECTOR, "#verify_code").send_keys("8888")
driver.find_element(By.CSS_SELECTOR, ".J-login-submit").click()

# 获取个人主页句柄
denglu = driver.current_window_handle
driver.switch_to.window(denglu)

# 定位搜索框，搜索手机
search = WebDriverWait(driver, 5, 1).until(lambda x: x.find_element_by_css_selector(".search_usercenter_text"))
search.send_keys("手机")
driver.find_element(By.CSS_SELECTOR, ".search_usercenter_btn").click()

# 获取搜索页句柄
sousuo = driver.current_window_handle
driver.switch_to.window(sousuo)

# 定位并点击第一个商品
phone = WebDriverWait(driver, 5, 1).until(lambda x: x.find_element(By.XPATH, "//li[1]/div/div[1]/a"))
phone.click()

# 获取商品页句柄
shouji = driver.current_window_handle
driver.switch_to.window(shouji)

# 加入购物车
driver.find_element(By.CSS_SELECTOR, "#join_cart").click()
# 关闭弹窗
chuangko = WebDriverWait(driver, 5, 1).until(lambda x: x.find_element_by_css_selector(".layui-layer-setwin"))
chuangko.click()
# 点击右上角购物车
phone = WebDriverWait(driver, 5, 1).until(lambda x: x.find_element(By.XPATH, "//div[@id='hd-my-cart']"))
phone.click()

# 获取购物车页句柄
gouwuche = driver.current_window_handle
driver.switch_to.window(gouwuche)
# 点击去结算
driver.find_element(By.CSS_SELECTOR, ".butpayin").click()

# 获取订单信息句柄
queren = driver.current_window_handle
driver.switch_to.window(queren)

# 点击提交订单
tijiao = WebDriverWait(driver, 7, 1).until(lambda x: x.find_element_by_css_selector("#submit_order"))
tijiao.click()

# 获取支付页句柄
zhifu = driver.current_window_handle
driver.switch_to.window(zhifu)

# 点击确认支付方式
zhifu_1 = WebDriverWait(driver, 5, 1).until(lambda x: x.find_element(By.LINK_TEXT, "确认支付方式"))
zhifu_1.click()

# 获取支付成功页句柄
chenggong = driver.current_window_handle
driver.switch_to.window(chenggong)

# 点击我的订单
chakan = WebDriverWait(driver, 5, 1).until(lambda x: x.find_element(By.LINK_TEXT, "我的订单"))
chakan.click()

# 暂停3秒
# time.sleep(3)
# 4.关闭/退出浏览器
# 关闭驱动对象
# driver.quit()
